//
//  MCTopUpRecordViewController.m
//  TLYL
//
//  Created by miaocai on 2017/7/10.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCWithdrawRecordViewController.h"
#import "MCTopUpRecrdTableViewCell.h"
#import "MCTopUpRecDetailViewController.h"
#import "MCTopUpMineFilterView.h"
#import "MCNaviButton.h"
#import "DatePickerView.h"
#import "MCNaviPopTopView.h"
#import "MJRefresh.h"
#import "MCGroupPaymentNewModel.h"
#import "MCButton.h"
#import "MCInputKaiHuView.h"
#import "MCUserDefinedAPIModel.h"
#import "MCWithdrawTableViewCell.h"
#import "MCCoverView.h"
#import "MCRechargeViewController.h"
#import "MCMineInfoModel.h"
#import "MCWithdrawRecDeltailViewController.h"
#import "MCRecordTool.h"

@interface MCWithdrawRecordViewController ()<UITableViewDelegate,UITableViewDataSource>

/**提款tableViewDataArray*/
@property (nonatomic,strong) NSMutableArray *tableViewDataDarwArray;
/**datePicker的最小时间*/
@property (nonatomic,strong) NSDate *minDate;
/**datePicker的最大时间*/
@property (nonatomic,strong) NSDate *maxDate;
/**datePicker 日期选择器*/
@property (nonatomic,  weak) DatePickerView  *datePicker;
/**充值的模型*/
@property (nonatomic,strong) MCTopUpRecordModel *topUpRecordModel;
/**筛选框*/
@property (nonatomic,  weak) MCNaviPopTopView *popView;
/**筛选框按钮*/
@property (nonatomic,  weak) MCNaviButton *btn;
/**查询状态*/
@property (nonatomic,strong) NSString *rechargeStates;
/**查询开始日期*/
@property (nonatomic,strong) NSDate *beginDate;
/**查询结束日期*/
@property (nonatomic,strong) NSDate *endDate;
@property (nonatomic,strong) NSDate *minDateEnd;
@property (nonatomic,strong) NSDate *minDateEndStart;

/**查询当前页*/
@property (nonatomic,strong) NSString *currentPageIndex;
/**查询当前页数量*/
@property (nonatomic,strong) NSString *currentPageSize;

/**查询下一页*/
@property (nonatomic,assign) int index;
@property (nonatomic,strong) MCGroupPaymentNewModel *paymentModel;
@property (nonatomic,strong) NSArray *arrData;
@property (nonatomic,assign) BOOL isShowPopView;
@property (nonatomic,weak) MCInputKaiHuView *viewPop;
@property (nonatomic,strong) NSString *insertTimeMin;
@property (nonatomic,strong) NSString *insertTimeMax;

@property (nonatomic,weak) UIScrollView *baseScrollView;
@property (nonatomic,weak) UITableView *tabRightView;
@property (nonatomic,strong) MCWithdrawModel *withdrawModel;

@property (nonatomic,weak) MCCoverView *cloverView;
@property (nonatomic,assign) int TransferType;

@property (nonatomic,assign) int rightRechargeStates;
@property (nonatomic,assign,getter=isDataMin) BOOL dataMin;


@end

@implementation MCWithdrawRecordViewController

#pragma mark - view life clycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"资金明细";
    [self addNavRightBtn];
    [self setUpUI];
    self.index = 1;
    [self configRequstNormalParmas];
    [self setExceptionViewFrame];
    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closePop:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.tabRightView addGestureRecognizer:singleTapGesture];
    
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    _isShowPopView=NO;
    [self loadDrawDataAndShow];
}

- (void)loadData{
    [self.tableViewDataDarwArray removeAllObjects];
    [self.tabRightView reloadData];
    [self hiddenExDataView];
    [self loadDrawDataAndShow];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.popView hidePopView];
    [self.viewPop hiden];
    [self.cloverView hidden];
    
}

#pragma mark - gesture actions
- (void)closePop:(UITapGestureRecognizer *)recognizer {
    _isShowPopView=NO;
    [self.popView hidePopView];
}

#pragma mark - configRequstNormalParmas
- (void)configRequstNormalParmas{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
//    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    self.minDate = [NSDate dateWithTimeIntervalSinceNow:-3*3600*24];
    self.maxDate = [NSDate date];
    self.rechargeStates = @"";
    self.beginDate = [NSDate date];
    self.endDate = [NSDate date];
    self.minDateEnd = self.minDate;
    self.minDateEndStart = self.minDate;
}

- (void)addNavRightBtn {
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setBackgroundImage:[UIImage imageNamed:@"debss"] forState:UIControlStateNormal];
    self.btn =btn;
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn sizeToFit];
    [btn addTarget:self action:@selector(allBtnClick:) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
}


- (void)setUpUI{
    
    UIScrollView *baseScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:baseScrollView];
    baseScrollView.pagingEnabled = YES;
    baseScrollView.showsVerticalScrollIndicator = NO;
    baseScrollView.showsHorizontalScrollIndicator = NO;
    baseScrollView.contentSize = CGSizeMake(3*G_SCREENWIDTH, G_SCREENHEIGHT);
    self.baseScrollView = baseScrollView;
    baseScrollView.scrollEnabled = NO;
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, G_SCREENWIDTH, MC_REALVALUE(40))];
    [self.view addSubview:topView];
    topView.backgroundColor = [UIColor whiteColor];
    NSArray *titleArr = @[@"类型",@"时间",@"金额",@"状态"];
    for (NSInteger i = 0; i<titleArr.count; i++) {
        UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(i*G_SCREENWIDTH*0.25, 0, G_SCREENWIDTH*0.25, MC_REALVALUE(40))];
        [topView addSubview:lable];
        lable.text = titleArr[i];
        lable.textColor =RGB(46, 46, 46);
        lable.font = [UIFont systemFontOfSize:12];
        lable.textAlignment = NSTextAlignmentCenter;
    }
    
    for (NSInteger i = 0; i<titleArr.count -1; i++) {
        UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake((i+1)*G_SCREENWIDTH*0.25, 40/4, 0.5, MC_REALVALUE(30))];
        [topView addSubview:lable];
        lable.backgroundColor =RGB(136, 136, 136);
        
    }
    //    /**tabView 创建*/
  
    // 提款记录
    UITableView *tabRight = [[UITableView alloc] initWithFrame:CGRectMake(13, 50, G_SCREENWIDTH-26, G_SCREENHEIGHT - kStatusBarAndNavigationBarHeight - 50 - kTabBarHeight -10) style:UITableViewStylePlain];
    [self.baseScrollView addSubview:tabRight];
    
    tabRight.delegate = self;
    tabRight.dataSource = self;
    self.tabRightView = tabRight;
    self.tabRightView.layer.cornerRadius = 6;
    self.tabRightView.clipsToBounds = YES;
    self.tabRightView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tabRightView.rowHeight = MC_REALVALUE(50);
    self.tabRightView.estimatedRowHeight = 0;
    self.tabRightView.estimatedSectionHeaderHeight = 0;
    self.tabRightView.estimatedSectionFooterHeight = 0;
    self.tabRightView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tabRightView registerClass:[MCWithdrawTableViewCell class] forCellReuseIdentifier:@"MCWithdrawTableViewCell"];
    self.tabRightView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDrawData)];
    self.tabRightView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadDrawDataAndShow];
    }];
   
    
    self.view.backgroundColor = RGB(231, 231, 231);
    
   
}



#pragma mark - touch event
- (void)recordBtnClick:(NSInteger)i{
    [self.viewPop hiden];
    self.popView.statusLabDetail.text = self.viewPop.dataArray[i];
    if (i == 0) {
        self.minDate = [NSDate dateWithTimeIntervalSinceNow:-3 * 3600 * 24];
        self.maxDate = [NSDate date];
    } else {

        self.minDate =[MCRecordTool getLaterDateFromDate:[NSDate date] withYear:0 month:-1 day:-3];
        self.maxDate = [NSDate dateWithTimeIntervalSinceNow:-4 * 3600 * 24];
        
    }

    self.minDateEnd = self.minDate;
    self.minDateEndStart = self.minDate;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSString *endDateStr = [dateFormatter stringFromDate:self.maxDate];
    self.beginDate = self.maxDate;
    self.endDate = self.maxDate;
    self.popView.endDateLabDetail.text = endDateStr;
    self.popView.startDateLabDetail.text = endDateStr;
}



- (void)allBtnClick:(UIButton *)btn{
    
    NSArray * arr=[MCUserDefinedAPIModel getGameRecordMarr];
    if (_isShowPopView) {
        _isShowPopView=NO;
        [self.popView hidePopView];
        
    }else{
        [self.view bringSubviewToFront:self.popView];
        _isShowPopView=YES;
        NSMutableArray *arrTemp = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            [arrTemp addObject:dic[@"name"]];
        }
    
            [self setShuaiXuanTiView:arr tempArr:arrTemp];
     
    }
    
    
}

- (void)setShuaiXuanTiView:(NSArray *)arr tempArr:(NSArray *)arrTemp{
    self.popView.titleLab.text = @"提款状态";
    //    self.popView.titleLabDetail.text = @"全部";
    typeof(self) weakself = self;
    self.popView.lotteryBlock = ^{
        weakself.viewPop.dataArray = @[@"全部",@"未处理",@"交易中",@"拒绝",@"交易成功",@"交易失败"];
        weakself.viewPop.cellDidSelectedTop = ^(NSInteger i) {
            NSString *str = @"";
            if (i == 0) {
            } else if(i == 1){
                str = @"0";
            }else{
                str = [NSString stringWithFormat:@"%ld",i-1];
            }
            self.rechargeStates = str;
            self.popView.titleLabDetail.text = weakself.viewPop.dataArray[i];
            [weakself.viewPop hiden];
        };
        [weakself.viewPop show];
    };
    self.popView.statusBlock = ^{
        if (weakself.datePicker) {
            [weakself.datePicker removeFromSuperview];
        }
        weakself.viewPop.dataArray = @[@"当前记录",@"历史记录"];
        [weakself.viewPop show];
        weakself.viewPop.cellDidSelected = ^(NSInteger i) {
            [weakself.viewPop hiden];
            
            weakself.popView.statusLabDetail.text = weakself.viewPop.dataArray[i];
            
            [weakself recordBtnClick:i];
        };
    };
    
    [weakself datePickerCallBack];
    self.popView.startBtnBlock = ^{
        [weakself.viewPop hiden];
        _isShowPopView=NO;
        [weakself loadDrawDataAndShow];
    };
    self.popView.dataSourceArray = arrTemp;
    self.popView.frame= CGRectMake(0, kStatusBarAndNavigationBarHeight, G_SCREENWIDTH, G_SCREENHEIGHT);
    [self.popView showPopView];
    self.popView.recordSelectedBlock = ^(NSInteger index) {
        NSDictionary *dic = arr[index];
        [weakself.btn setTitle:dic[@"name"] forState:UIControlStateNormal];
        [weakself.btn sizeToFit];
        [weakself loadDrawDataAndShow];
    };
}
#pragma mark - load data
- (void)loadDrawDataAndShow{
    [self.tableViewDataDarwArray removeAllObjects];
    MCGroupPaymentNewModel *model = [[MCGroupPaymentNewModel alloc] init];
    self.paymentModel = model;
    [model refreashDataAndShow];
    __weak typeof(self)weakSelf = self;
    __weak MCGroupPaymentNewModel *weakNewModel_Self = model;
    model.callBackSuccessBlock = ^(ApiBaseManager *manager) {
        NSDictionary * dic = manager.ResponseRawData;
        [weakNewModel_Self setPayMentArrWithData:dic];
        weakSelf.arrData = weakNewModel_Self.AllRecPay;
        
    };
    self.tabRightView.mj_footer.hidden=NO;
    self.withdrawModel->_drawingsState = self.rechargeStates;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSString *dateTemps = [dateFormatter stringFromDate:self.beginDate];
    NSString *dateTempe = [dateFormatter stringFromDate:self.endDate];
    self.withdrawModel->_beginDate = [NSString stringWithFormat:@"%@ 00:00:00",dateTemps];
    self.withdrawModel->_endDate = [NSString stringWithFormat:@"%@ 23:59:59",dateTempe];
    self.withdrawModel->_currentPageIndex = @"1";
    self.withdrawModel->_currentPageSize = @"15";
    self.withdrawModel.callBackSuccessBlock = ^(id manager) {
        [weakSelf.tabRightView.mj_header endRefreshing];
        [weakSelf.tabRightView.mj_footer endRefreshing];
        if ([manager isKindOfClass:[NSString class]]) {
            [weakSelf.tableViewDataDarwArray removeAllObjects];
            [weakSelf.tabRightView reloadData];
            return ;
            
        }
        weakSelf.tableViewDataDarwArray = [MCWithdrawModel mj_objectArrayWithKeyValuesArray:manager[@"ModelList"]];
        if (weakSelf.tableViewDataDarwArray.count == 0) {
            [weakSelf showExDataView];
        }else{
            [weakSelf hiddenExDataView];
        }
        if (weakSelf.tableViewDataDarwArray.count==[manager[@"DataCount"] integerValue]) {
            weakSelf.tabRightView.mj_footer.hidden=YES;
        }
        [weakSelf.tabRightView reloadData];
    };

    self.withdrawModel.callBackFailedBlock = ^(id manager, NSDictionary *errorCode) {
        [weakSelf tableViewEndRefreshing];
        [weakSelf showExcaptionView:errorCode];
    };

    [BKIndicationView showInView:self.view];
    [self.withdrawModel refreashDataAndShow];
    
}



- (void)loadMoreDrawData{
    
    self.tabRightView.mj_footer.hidden=NO;
    self.withdrawModel->_currentPageIndex = [NSString stringWithFormat:@"%d",++self.index];
    __weak typeof(self) weakSelf = self;
    self.withdrawModel.callBackSuccessBlock = ^(id manager) {
        NSArray *arr = [MCWithdrawModel mj_objectArrayWithKeyValuesArray:manager[@"ModelList"]];
        [weakSelf.tableViewDataDarwArray addObjectsFromArray:arr];
        if (weakSelf.tableViewDataDarwArray.count == 0) {
            
            [weakSelf showExDataView];
        }else{
            [weakSelf hiddenExDataView];
        }
        
        if (weakSelf.tableViewDataDarwArray.count==[manager[@"DataCount"] integerValue]) {
            weakSelf.tabRightView.mj_footer.hidden=YES;
        }
        [weakSelf.tabRightView reloadData];
        
        [weakSelf.tabRightView.mj_header endRefreshing];
    };
    self.withdrawModel.callBackFailedBlock = ^(id manager, NSDictionary *errorCode) {
        [weakSelf tableViewEndRefreshing];
        [weakSelf showExcaptionView:errorCode];
    };
    [BKIndicationView showInView:self.view];
    [self.withdrawModel refreashDataAndShow];
}

- (void)tableViewEndRefreshing{
    [self.tabRightView.mj_footer endRefreshing];
    [self.tabRightView.mj_header endRefreshing];

}

- (void)datePickerCallBack{
    __weak typeof(self) weakself = self;
    self.popView.startDateBlock = ^{
        weakself.minDate = weakself.minDateEnd;
        weakself.datePicker.showDate = weakself.beginDate;
        self.datePicker.cancelBlock = ^{
            [UIView animateWithDuration:0.25 animations:^{
                [self.datePicker removeFromSuperview];
               
            }];
        };
        
        self.datePicker.sureBlock = ^(NSString *selectDateStr) {
            weakself.popView.startDateLabDetail.text = selectDateStr;
            NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
            [dataFormatter setDateFormat:@"yyyy/MM/dd"];
            weakself.minDate = [dataFormatter dateFromString:selectDateStr];
            weakself.minDateEndStart = weakself.minDate;
            weakself.beginDate = [dataFormatter dateFromString:selectDateStr];
            [UIView animateWithDuration:0.25 animations:^{
                [self.datePicker removeFromSuperview];
                
            }];
        };
        
    };
    
    self.popView.endDateBlock = ^{
        weakself.minDate = weakself.minDateEndStart;
        weakself.datePicker.showDate = weakself.endDate;
        [self.viewPop hiden];
        self.datePicker.cancelBlock = ^{
            [UIView animateWithDuration:0.25 animations:^{
                [self.datePicker removeFromSuperview];
            }];
        };
        self.datePicker.sureBlock = ^(NSString *selectDateStr) {
            
            weakself.popView.endDateLabDetail.text = selectDateStr;
            NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
            [dataFormatter setDateFormat:@"yyyy/MM/dd"];
            //            weakself.maxDate = [dataFormatter dateFromString:selectDateStr];
            weakself.endDate = [dataFormatter dateFromString:selectDateStr];
            
            [UIView animateWithDuration:0.25 animations:^{
                [self.datePicker removeFromSuperview];
            }];
        };
        
    };
    
}

#pragma mark - tableView dataSource and delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.tableViewDataDarwArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MCWithdrawTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MCWithdrawTableViewCell"];
    cell.dataSource = self.tableViewDataDarwArray[indexPath.row];
    cell.backgroundColor = [UIColor redColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.cloverView.dataArr = self.arrData;
    self.cloverView.dataSourceD = self.tableViewDataDarwArray[indexPath.row];
    [self.cloverView show];

}
- (void)dealloc{
    NSLog(@"MCTopUpRecordViewController----dealloc");
}

#pragma mark - getter and setter

- (void)tap{
    _isShowPopView=NO;
    self.popView.hidden = YES;
    [self.viewPop hiden];
}
- (MCCoverView *)cloverView{
    if (_cloverView == nil) {
        MCCoverView *cloverView = [[MCCoverView alloc] initWithFrame:CGRectMake(0, kStatusBarAndNavigationBarHeight, G_SCREENWIDTH, G_SCREENHEIGHT - kStatusBarAndNavigationBarHeight)];
        cloverView.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.4];
        __weak typeof(self) weakself = self;
        [self.navigationController.view addSubview:cloverView];
        _cloverView = cloverView;
        __weak typeof(cloverView) weakClo = cloverView;
        cloverView.cancelBlock = ^{
            [weakClo hidden];
            [weakself.tabRightView reloadData];
        };
        cloverView.coverViewBlock = ^{
            [weakClo hidden];
            MCMineInfoModel * mineInfoModel = [MCMineInfoModel sharedMCMineInfoModel];
            if ([mineInfoModel.UserType intValue] ==1) {
                [SVProgressHUD showInfoWithStatus:@"您无提款权限！"];
                return;
            }
                MCWithdrawRecDeltailViewController *re1 = [[MCWithdrawRecDeltailViewController alloc] init];
                [weakself.navigationController pushViewController:re1 animated:YES];
          
            
            
        };
        
    }
    return _cloverView;
    
    
}




- (NSMutableArray *)tableViewDataDarwArray{
    
    if (_tableViewDataDarwArray == nil) {
        _tableViewDataDarwArray = [NSMutableArray array];
    }
    return _tableViewDataDarwArray;
}

- (DatePickerView *)datePicker{
    
    if (_datePicker == nil) {
        DatePickerView *datePicker =[[[NSBundle mainBundle] loadNibNamed:@"DatePickerView" owner:self options:0] lastObject];
        datePicker.minDate = self.minDate;
        datePicker.maxDate = self.maxDate;
        datePicker.frame =CGRectMake(0, self.view.frame.size.height  - 200 -kTabBarHeight, self.view.frame.size.width, 200);
        datePicker.Datetitle =@"日期选择";
        [self.popView addSubview:datePicker];
        _datePicker = datePicker;
    }
    return _datePicker;
}

- (MCTopUpRecordModel *)topUpRecordModel{
    
    if (_topUpRecordModel == nil) {
        MCTopUpRecordModel *model = [[MCTopUpRecordModel alloc] init];
        _topUpRecordModel = model;
    }
    return _topUpRecordModel;
}

- (MCNaviPopTopView *)popView{
    
    if (_popView == nil) {
        MCNaviPopTopView * popView = [[MCNaviPopTopView alloc] init];
        [self.navigationController.view addSubview:popView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [popView addGestureRecognizer:tap];
        _popView = popView;
    }
    return _popView;
}

- (MCInputKaiHuView *)viewPop{
    if (_viewPop == nil) {
        MCInputKaiHuView *viewStatus = [[MCInputKaiHuView alloc] init];
        [self.navigationController.view addSubview:viewStatus];
        _viewPop = viewStatus;
    }
    return _viewPop;
}

- (MCWithdrawModel *)withdrawModel{
    if (_withdrawModel == nil) {
        MCWithdrawModel *model = [[MCWithdrawModel alloc] init];
        _withdrawModel = model;
    }
    return _withdrawModel;
}

- (void)setExceptionViewFrame{
    CGRect rect = CGRectMake(MC_REALVALUE(13), MC_REALVALUE(13) + MC_REALVALUE(40), G_SCREENWIDTH - MC_REALVALUE(26), G_SCREENHEIGHT-MC_REALVALUE(66) - kStatusBarAndNavigationBarHeight -kTabBarHeight);
    self.noDataWin.frame = rect;
    self.errNetWin.frame = rect;
    self.errDataWin.frame = rect;
}
@end

